var api = require('../config/api.js');
var app = getApp();

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
	return new Promise(function (resolve, reject) {
		wx.request({
			url: url,
			data: data,
			method: method,
			header: {
				'Content-Type': 'application/json',
				'X-Litemall-Token': wx.getStorageSync('token')
			},
			success: function (res) {
				console.log('接口返回：',res)
				if (res.statusCode == 200) {

					if (res.data.error_code == 401) {
						// 清除登录相关内容
						try {
							wx.removeStorageSync('userInfo');
							wx.removeStorageSync('token');
							wx.removeStorageSync('openid');
						} catch (e) {
							// Do something when catch error
						}
						// 切换到首页（登录）页面
						wx.navigateTo({
							url: '/pages/home/home'
						});
					} else {
						resolve(res.data);
					}
				} else {
					reject(res.errMsg);
				}

			},
			fail: function (err) {
				reject(err)
			}
		})
	});
}

function redirect(url) {

	//判断页面是否需要登录
	if (false) {
		wx.redirectTo({
			url: '/pages/register/register'
		});
		return false;
	} else {
		wx.redirectTo({
			url: url
		});
	}
}


module.exports = {
	request,
	redirect
}